import React, { useState, useEffect } from 'react';
import { PageContainer, WaterMark } from '@ant-design/pro-layout';
import { Form, Card, Input, Button, message, Select } from 'antd';
import '../index.less'
import { history } from 'umi';
import UploadImage from '@/components/UploadImage'
import type { cropOptionsType, ImageListType } from '@/components/UploadImage'
import Tinymce from '@/components/Tinymce'
import { getUpPic, getBannerDetail, editBannerDetail } from '../service'

const { Option } = Select

export default (props: any): React.ReactNode => {
    const [adImageList, setAdImageList] = useState<ImageListType[]>([]);
    const [adType, setAdType] = useState<string>('1');
    const [content, setContent] = useState<string>('');
    const [editorHtml, setEditorHtml] = useState<string>('');

    const { id } = props.location?.state

    const [form] = Form.useForm();
    const layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 6 },
    };
    const itemlayout = {
        wrapperCol: { span: 10 },
    };
    const tailLayout = {
        wrapperCol: { offset: 4, span: 16 },
    };


    //相当于componentDidMount
    useEffect(() => {
        (async function onCreateFun() {
            if (id) {
                const response = await getBannerDetail({ id: id })
                if (response && response instanceof Object) {
                    const { banner, ad_type, sort, ad_content } = response.data.info
                    setAdImageList([{
                        uid: '-1',
                        name: "",
                        status: 'done',
                        url: banner,
                    }])
                    setAdType(`${ad_type}`)
                    setEditorHtml(ad_content)
                    form.setFieldsValue({
                        ad_type: `${ad_type}`,
                        sort: `${sort}`,
                        contentUrl: ad_type === '2' ? ad_content : ''
                    })
                }
            }
        })();
    }, [])


    const onFinish = async (params: any) => {
        console.log(params)
        const response = await editBannerDetail(params = { ...params, banner_id: id, banner: adImageList[0].url, content: adType === '1' ? content : params.content });
        if (response && response instanceof Object) {
            message.success(response.message)
            history.go(-1)
        }
    };

    const cropOptions: cropOptionsType = {
        modalTitle: "上传广告图片",
    }

    /**
     * 
     * @param list 获取上传的图片集合
     */
    const onAdImageListChange = (list: ImageListType[]) => {
        setAdImageList([...list])
    }

    /**
     * 内容类型
     */
    const onContentTypeChange = (value: string) => {
        setAdType(value)
    }

    /**
     * 
     * @param text 富文本内容
     */
    const handleEditorTextChange = (text: string) => {
        setContent(text)
    }
    /**
     * 
     * @param blobInfo 富文本上传图片
     * @param success 
     * @param failure 
     */
    const handleImageUpload = async (blobInfo: any, success: Function, failure: Function) => {
        const response = await getUpPic({ img_type: "testUp", img_byte: "data:image/jpeg;base64," + blobInfo.base64() });
        if (response && response instanceof Object) {
            success(response.data)
        } else {
            failure('上传失败')
        }
    }
    return (
        <PageContainer>
            <Card>
                <WaterMark content="御码科技" className='app-container'>
                    <Form
                        {...layout}
                        initialValues={{ location_id: '1', ad_type: adType }}
                        form={form}
                        name="basic"
                        onFinish={onFinish}
                    >
                        <Form.Item
                            label="广告图片："
                            name="banner"
                            rules={[{
                                required: true, validator: (rule, value = '', callback) => {
                                    if (adImageList.length == 0) {
                                        return Promise.reject('您还没选择广告图片');
                                    } else {
                                        return Promise.resolve()
                                    }
                                }
                            }]}
                        >
                            {/* cropOptions 可以不传，imgNum：可以不传，默认一张 isModal 可以不传，默认不是弹窗*/}
                            <UploadImage
                                cropOptions={cropOptions}
                                imgNum={1}
                                isModal={false}
                                imageList={adImageList}
                                onAdImageListChange={onAdImageListChange} />
                        </Form.Item>
                        <Form.Item
                            label="广告位置："
                            name="location_id"
                            rules={[{ required: true, message: '请输入排序' }]}
                        >
                            <Select
                                placeholder="请选择"
                                allowClear
                            >
                                <Option value="1">收听页面</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="内容类型："
                            name="ad_type"
                            rules={[{ required: true, message: '请输入排序' }]}
                        >
                            <Select
                                placeholder="请选择"
                                allowClear
                                onChange={onContentTypeChange}
                            >
                                <Option value="1">图文</Option>
                                <Option value="2">连接</Option>
                                <Option value="3">无内容</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="排序"
                            name="sort"
                            rules={[{ required: true, message: '请输入排序' }, {
                                required: false,
                                pattern: new RegExp(/^[1-9]\d*$/, "g"),
                                message: '您还没填写正确的排序'
                            }]}
                        >
                            <Input placeholder='请输入排序' allowClear maxLength={10} />
                        </Form.Item>
                        {
                            adType === '2' ? (
                                <Form.Item
                                    label="url:"
                                    name="contentUrl"
                                    rules={[{ required: true, message: '请输入排序' }, {
                                        required: false,
                                        pattern: /^(https?|ftp|file):\/\/.+$/,
                                        message: '您还没填写正确的链接'
                                    }]}
                                >
                                    <Input placeholder='链接必须以http/https开头的全url' allowClear />
                                </Form.Item>
                            ) : (
                                adType === '1' ? (
                                    <Form.Item
                                        {...itemlayout}
                                        label="文本内容"
                                        name="contentHtml"
                                        rules={[{
                                            required: true, validator: (rule, value = '', callback) => {
                                                if (Object.keys(content).length == 0) {
                                                    return Promise.reject('您还没填写文本内容');
                                                } else {
                                                    return Promise.resolve()
                                                }
                                            }
                                        }]}
                                    >
                                        <Tinymce editorHtml={editorHtml} handleEditorTextChange={handleEditorTextChange} handleImageUpload={handleImageUpload} />
                                    </Form.Item>
                                ) : null
                            )
                        }
                        <Form.Item  {...tailLayout}>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                        </Form.Item>
                    </Form>
                </WaterMark>
            </Card>
        </PageContainer>
    );
};
